package cn.lg.soar.redis.manager;

import cn.lg.soar.core.manager.LocalTokenStateManager;
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @author luguoxiang
 * @date 2022/4/7
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class RedisTokenStateManager extends LocalTokenStateManager {

    private final RedisTemplate<String, Long> redisTemplate;
    private final static String PREFIX = "$:";

    public RedisTokenStateManager(RedisTemplate<String, Long> redisTemplate) {
        super();
        this.redisTemplate = redisTemplate;
    }
    public RedisTokenStateManager(RedisTemplate<String, Long> redisTemplate, Cache<String, Long> cache) {
        super(cache);
        this.redisTemplate = redisTemplate;
    }
    public RedisTokenStateManager(RedisTemplate<String, Long> redisTemplate, long cacheSize, Duration expire) {
        super(cacheSize, expire);
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void put(String id, Long value, long expire) {
        redisTemplate.opsForValue().set(PREFIX + id, value, expire, TimeUnit.MILLISECONDS);
        cache.put(id, value);
    }

    @Override
    public Long get(String id) {
        return cache.get(id, key -> redisTemplate.opsForValue().get(PREFIX + key));
    }

    @Override
    public void remove(String id) {
        redisTemplate.delete(PREFIX + id);
        cache.invalidate(id);
    }
}
